package com.skit.mine.span;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;

import com.skit.mine.R;


public class HtmlTextSpan extends ClickableSpan {
    private static HtmlTextSpan htmlTextSpan;
    private Context mContext;
    private OnClickListener mOnClickListener;
    private int mTextColor;

    //点击事件
    public interface OnClickListener {
        void onClick(View view);
    }

    public void setTextColor(@ColorInt int color) {
        mTextColor = color;
    }


    private HtmlTextSpan(Context context) {
        mContext = context;
        mTextColor = mContext.getResources().getColor(R.color.colorAccent);
    }

    @Override
    public void onClick(@NonNull View widget) {
        if (mOnClickListener != null) {
            mOnClickListener.onClick(widget);
        }
    }

    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        super.updateDrawState(ds);
        ds.setColor(mTextColor);
        ds.setUnderlineText(false);
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    /**
     * 给TextView设置Html文字
     *
     * @param textView 目标TextView
     * @param id       文字id
     * @return HtmlTextSpan
     */
    public static HtmlTextSpan setHtmlText(TextView textView, @StringRes int id) {
        htmlTextSpan = new HtmlTextSpan(textView.getContext());
        CharSequence ss = textView.getResources().getText(id);
        textView.setText(ss);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence src = textView.getText();
        if (src instanceof Spannable) {
            int end = src.length();
            Spannable spannable = (Spannable) src;
            URLSpan[] spans = spannable.getSpans(0, end, URLSpan.class);

            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(src);
            spannableStringBuilder.clearSpans();

            for (URLSpan span : spans) {
                spannableStringBuilder.setSpan(htmlTextSpan, spannable.getSpanStart(span), spannable.getSpanEnd(span), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            textView.setText(spannableStringBuilder);
        }
        return htmlTextSpan;
    }

}

